<?php

class wxmenu_service extends service {
	public function __construct() {
		$this->wxmenu_db = model('wxmenu');
	}
	
	public function add($params){		
		if(empty($params['parent_id'])){
			$params['parent_id'] = 0;
		}else{
			$count = $this->wxmenu_db->where(array('id'=>array('eq',(int)$params['parent_id'])))->count();
			if($count < 1){
				$this->error = '父菜单不存在';
				return false;
			}
		}
		$data = array();
		$data['name'] = $params['name'];
		$data['pid'] = $params['parent_id'];
		$data['type'] = $params['type'];
		$data['keyword'] = $params['keyword'];
		$data['likes'] = $params['likes'];
		$data['status'] = $params['status'];
		$data['sort'] = $params['sort'];
		$result = $this->wxmenu_db->update($data);
    	if(!$result){
    		$this->error = $this->wxmenu_db->getError();
			return FALSE;
    	}else{
    		return TRUE;
    	}		
	}
	
	public function delete($params){
		if($this->has_child($params['id'])){
			$this->error = '请先删除子菜单';
			return FALSE;
		}
		$data = array();
		$data['id'] = array('IN', $params['id']);
		$result = $this->wxmenu_db->where($data)->delete();
    	if(!$result){
			$this->error = $this->wxmenu_db->getError();
    		return FALSE;
    	}else{
    		return TRUE;
    	}	
	}
	
	public function has_child($params){
		$params_ids = explode(',',$params[0]);
		for($i=0; $i<count($params_ids); $i++){
			$tem_data[] = $this->wxmenu_db->where(array('pid' =>array('eq',$params_ids[$i])))->count();
			if($tem_data[$i] > 0){
				return TRUE;
			}
		}
		return FALSE;
	}
	public function edit($params){
		if((int)$params['id'] < 1){
			$this->error = '父菜单不存在';
			return FALSE;
		}		
		$data = array();
		$data['id'] = $params['id'];
		$data['name'] = $params['name'];
		$data['pid'] = $params['parent_id'];
		$data['type'] = $params['type'];
		$data['keyword'] = $params['keyword'];
		$data['likes'] = $params['likes'];
		$data['status'] = $params['status'];
		$data['sort'] = $params['sort'];
		$result = $this->wxmenu_db->update($data);
    	if($result === FALSE){
			$this->error = $this->wxmenu_db->getError();
    		return FALSE;
    	}else{
    		return TRUE;
    	}	
	}
	
	public function ajax_son_class($params){
		if((int)$params['id'] < 1){
			$this->error = '菜单不存在';
			return FALSE;
		}
		$result = $this->wxmenu_db->where(array('pid' =>array('eq',$params['id'])))->select();
		foreach($result as $key => $value){
			$result[$key]['row'] = $this->wxmenu_db->where(array('pid' =>array('eq',$value['id'])))->count();
		}
		if(!$result){
			$this->error = $this->wxmenu_db->getError();
		}
		return $result;
	}
	
	public function get_category_by_id($id,$field = FALSE){
		if((int)$id < 1){
			$this->error = '菜单不存在';
			return FALSE;
		}
		$result = $this->wxmenu_db->find($id);
		$result['category_id'] = $this->get_parent_id($result['id']);
		$result['parent_name'] = $this->create_cat_format($id);
		if(!$result){
			$this->error = $this->wxmenu_db->getError();
		}
		if($field) return $result[$field]; 
		return $result;
	}
	
	public function create_cat_format($id){
		$cat_str = '';
		$info = $this->get_parent($id);
		array_push($info,$id);
		$cat_arr = $this->wxmenu_db->where(array('id'=>array('IN',$info)))->getField('name',TRUE);
		foreach ($cat_arr as $key => $value) {
			if($key == count($cat_arr)-1){
				$cat_str .= $value;
			}else{
				$cat_str .= $value.' > ';
			}
		}
		return $cat_str;
	}
	
	public function get_parent($id){
    	if($id < 0){
    		$this->error = '菜单不存在';
    		return FALSE;
    	}
		static $flist=array();
		$row = $this->wxmenu_db->where(array('id'=>$id))->find();
		if(!$row){
			$this->error = '菜单不存在';
			return FALSE;
		}
		if ((int)$row['pid'] != 0){
			$classFID  = $row['pid'];
			$flist[] = $classFID;
			$this->get_parent($classFID);
		}else{
			$classFID  = $row['pid'];
			$flist[] = $classFID;
		}
		if(!empty($flist)){
			return $flist;
		}else{
			$this->error = '该菜单没有父级菜单';
			return FALSE;
		}
	}
	
	public function get_parent_id($id){
    	if($id < 0){
    		$this->error = '菜单不存在';
    		return FALSE;
    	}
		static $flist = array();
		$row = $this->wxmenu_db->where(array('id'=>$id))->find();
		if((int) $row['pid'] != 0){
			$classFID  = $row['pid'];
			$flist[] = $row['id'];
			$this->get_parent_id($classFID);
		} elseif($row['pid'] == 0){
			$flist[] = $row['id'];
		}
		array_push($flist,0);
		$ids = implode(",",$flist);
		return $ids;
	}
	
	public function ajax_edit($params){
		unset($params['page']);
	    $result = $this->wxmenu_db->update($this->assembl_array($params));
    	if(!$result){
    		$this->error = $this->wxmenu_db->getError();
			return FALSE;
    	}else{
    		return TRUE;
    	}	
	}
	
	public function get_menu_tree(){
		$_catinfo = $this->wxmenu_db->select();
		if(!$_catinfo){
    		$this->error = $this->wxmenu_db->getError();
    		return FALSE;
    	}
		$first = array(
			'id' => '0',
            'name' => '顶级菜单',
            'pid' => '-1'
		);
		array_unshift($_catinfo,$first);
    	return $_catinfo;
	}
	
	public function get_menu_list($store_id=1){
		$_catinfo = $this->wxmenu_db->where(array('pid'=>0,'status'=>1,'mid'=>$store_id))->select();
		if(!$_catinfo){
    		$this->error = $this->wxmenu_db->getError();
    		return FALSE;
    	}
		
		foreach ($_catinfo as $key) {
            $nextmenu = $this->wxmenu_db->where(array('pid'=>$key['id'],'status'=>1,'mid'=>$store_id))->select();
            if (count($nextmenu) != 0) {//没有下级栏目			
				foreach ($nextmenu as $key2){
					if($key2['type'] == 1){				
						$kk[] = array('type' => 'view', 'name' => $key2['name'], 'url' => $key2['likes']);	
					}else if ($key2['type'] == 2) {
						$kk[] = array('type' => $key2['weixin_key'], 'name' => $key2['name'], 'key' => $key2['weixin_key']);	
					}else{
						$kk[] = array('type' => 'click', 'name' => $key2['name'], 'key' => $key2['keyword']);				
					}				
				}
				$keyword['button'][] = array('name' => $key['name'], 'sub_button' => $kk);
				$kk = '';
			} else {
				if($key['type'] == 1){
					$keyword['button'][] = array('type' => 'view', 'name' => $key['name'], 'url' => $key['likes']);
				}else if ($key['type'] == 2) {
					$keyword['button'][] = array('type' => $key['weixin_key'], 'name' => $key['name'], 'key' => $key['weixin_key']);	
				}else {
					$keyword['button'][] = array('type' => 'click', 'name' => $key['name'], 'key' => $key['keyword']);
				}
			}
        }
    	return json_encode($keyword);
	}
	
	public function get_alimenu_list(){
		$_catinfo = $this->wxmenu_db->where(array('pid'=>0,'status'=>1))->select();
		
		if(!$_catinfo){
    		$this->error = $this->wxmenu_db->getError();
    		return FALSE;
    	}
		
		foreach ($_catinfo as $key){
            $nextmenu = $this->wxmenu_db->where(array('pid'=>$key['id'],'status'=>1))->select();
            if (count($nextmenu) != 0) {//没有下级栏目			
                foreach ($nextmenu as $key2){
					if($key2['type'] == 1){						
						$kk[] = array('actionParam' => urlencode(mb_convert_encoding($key2['likes'],"GBK","UTF-8")), 'actionType' => 'link', 'name' => urlencode(mb_convert_encoding($key2['name'],"GBK","UTF-8")));	
					}elseif($key2['type'] == 2){
					}else{
						$kk[] = array('actionParam' => urlencode(mb_convert_encoding($key2['keyword'],"GBK","UTF-8")), 'actionType' => 'out', 'name' => urlencode(mb_convert_encoding($key2['name'],"GBK","UTF-8")));	
					}
				}
                $keyword['button'][] = array('name' => urlencode(mb_convert_encoding($key['name'],"GBK","UTF-8")), 'subButton' => $kk);
                $kk = '';		   
		     } else {
				if($key['type']== 1){
					$keyword['button'][] = array('actionParam' => urlencode(mb_convert_encoding($key['likes'],"GBK","UTF-8")), 'actionType' => 'link', 'name' => urlencode(mb_convert_encoding($key['name'],"GBK","UTF-8")));
				}elseif($key2['type'] == 2){
				}else {				
					$keyword['button'][] = array('actionParam' => urlencode(mb_convert_encoding($key['keyword'],"GBK","UTF-8")), 'actionType' => 'out', 'name' => urlencode(mb_convert_encoding($key['name'],"GBK","UTF-8")));
				}		 
			}
        }
		
        $dat = json_encode($keyword);
		$dat = urldecode($dat);
    	return $dat;
	}
	
	public function assembl_array($params){
		if((int)$params['id'] < 1){
			$this->error = '参数错误';
			return FALSE;
		}
		$data = array();
		$data_key = array_keys($params);
		$data_value = array_values($params);
		foreach($data_key as $key => $value){
			$data[$value] = $data_value[$key];
		}
		return $data;
	}
	
	public function curl($appid,$secret)
    {
		$ch = curl_init(); 
		curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret); 
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
		$tmpInfo = curl_exec($ch); 
		if (curl_errno($ch)) {  
			echo 'Errno'.curl_error($ch);
		}
		curl_close($ch); 
		
		$arr= json_decode($tmpInfo,true);
		return $arr;
    }
	
	public function curl_menu($ACCESS_TOKEN,$data)
    {
		$ch = curl_init(); 
		curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$ACCESS_TOKEN); 
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
		$tmpInfo = curl_exec($ch); 
		if (curl_errno($ch)) {		
			echo 'Errno'.curl_error($ch);
		}
		curl_close($ch); 
		$arr= json_decode($tmpInfo,true);
		return $arr;
    }
}